import axios from 'axios';
import { defaultConfig } from './config';

class BaseApi {
  constructor(config = {}) {
    this.service = config.service || '';
    this.baseUrl = this.generateBaseUrl();
    this.config = { ...defaultConfig, ...config };
    this.instance = axios.create(this.config);
    this.setupInterceptors();
  }

  setupInterceptors() {
    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => config,
      (error) => Promise.reject(error)
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response) => this.handleSuccess(response),
      (error) => this.handleError(error)
    );
  }

  handleSuccess(response) {
    const { data } = response;
    if (data.code === 0) {
      return data.data;
    } else {
      this.showError(data.message);
      return Promise.reject(data);
    }
  }

  handleError(error) {
    const message = error.response?.data?.message || 'Network error';
    this.showError(message);
    return Promise.reject(error);
  }

  showError(message) {
    if (window.toast) {
      window.toast.error(message);
    } else {
      console.error('API Error:', message);
    }
  }

  // HTTP请求方法
  constructor(config = {}) {
    this.config = { ...defaultConfig, ...config };
    this.instance = axios.create(this.config);
    this.setupInterceptors();
    this.setupHTTPMethods();
  }

  // 动态生成HTTP请求方法
  generateBaseUrl() {
    const domain = process.env.REACT_APP_DOMAIN || '';
    const platform = process.env.REACT_APP_PLATFORM || '';
    const platformMap = { UCC: 'useside', UMC: 'management' };
    const platformSuffix = platformMap[platform] || '';
    return `${domain}/api/${this.service}/${platformSuffix}`.replace(/\/+/g, '/');
  }

  setupHTTPMethods() {
    // 定义HTTP方法及其参数类型
    const methods = {
      get: 'params',
      head: 'params',
      delete: 'params',
      post: 'data',
      put: 'data',
      patch: 'data'
    };

    // 动态生成请求方法
    Object.keys(methods).forEach(method => {
      this[method] = (url, dataOrParams = {}, config = {}) => {
        const paramType = methods[method];
        return this.request({
          method,
          url,
          [paramType]: dataOrParams,
          ...config
        });
      };
    });
  }

  // 通用请求方法
  request(options) {
    // 合并自定义请求头
    options.headers = {
      ...this.config.headers,
      ...options.headers
    };

    // 处理URL参数
    if (options.params && typeof options.params === 'object') {
      options.paramsSerializer = (params) => {
        return Object.keys(params)
          .map(key => {
            const value = params[key];
            // 数组参数处理
            if (Array.isArray(value)) {
              return value.map(v => `${encodeURIComponent(key)}[]=${encodeURIComponent(v)}`).join('&');
            }
            return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
          })
          .join('&');
      };
    }

    // 处理不同内容类型的请求参数
    if (options.contentType === 'form-data') {
      options.headers = {
        ...options.headers,
        'Content-Type': 'multipart/form-data',
      };
      // 转换为FormData
      const formData = new FormData();
      Object.keys(options.data || {}).forEach(key => {
        const value = options.data[key];
        // 处理多文件上传
        if (Array.isArray(value) && value.length > 0 && value[0] instanceof File) {
          value.forEach(file => {
            formData.append(key, file, file.name);
          });
        } else if (value instanceof File) {
          formData.append(key, value, value.name);
        } else {
          formData.append(key, value);
        }
      });
      options.data = formData;
    } else if (options.contentType === 'json' || !options.contentType) {
      // JSON类型参数处理
      options.headers = {
        ...options.headers,
        'Content-Type': 'application/json',
      };
      // 确保数据是JSON字符串或可序列化对象
      if (options.data && typeof options.data !== 'string') {
        options.data = JSON.stringify(options.data);
      }
    } else if (options.contentType === 'urlencoded') {
      // URL编码类型参数处理
      options.headers = {
        ...options.headers,
        'Content-Type': 'application/x-www-form-urlencoded',
      };
      // 转换为URL编码字符串
      if (options.data && typeof options.data === 'object') {
        options.data = new URLSearchParams(options.data).toString();
      }
    }

    return this.instance(options);
  }

  // 动态设置BaseURL
  setBaseURL(baseURL) {
    this.instance.defaults.baseURL = baseURL;
  }

  // 添加请求拦截器
  useRequestInterceptor(onFulfilled, onRejected) {
    return this.instance.interceptors.request.use(onFulfilled, onRejected);
  }

  // 添加响应拦截器
  useResponseInterceptor(onFulfilled, onRejected) {
    return this.instance.interceptors.response.use(onFulfilled, onRejected);
  }
}

export default BaseApi;